package com.ratingbay.console.naivequery;

import java.util.*;
 
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

import com.ratingbay.console.model.*;

public class GameNaiveQuery{
	private GameNaiveQuery(){
	}
	private static GameNaiveQuery self = null;
    public static GameNaiveQuery getInstance(){
    	if(null == self){
    		self = new GameNaiveQuery();
    	}
        return self;
    }


    //used in class inner
    protected String getIdsStr(List<Long> idList){
        String idsStr = "(";
        Iterator<Long> it = idList.iterator();
        while(it.hasNext()){
            idsStr += it.next();
            if(it.hasNext()) idsStr += ",";
        }
        idsStr += ")";
        return idsStr;
    }


    public List<Long> findRelatedGameIdsByGameAndUsers(Long idGame, List<Long> tUserIds,
        int pageNum, int pageSize){
        EntityManagerFactory emf = NaiveQuery.getInstance().getEntityManagerFactory();
        EntityManager em = emf.createEntityManager();

        Long limit = (long)pageSize;
        Long offset = (long)pageNum * pageSize;
        String tUserIdsStr = getIdsStr(tUserIds);

        String sql = "select distinct t.idGame from tweet t where t.id_game <> " + idGame +
            " and t.user_id in " + tUserIdsStr + " limit "+ limit +" offset " + offset;
        Query query =  em.createNativeQuery(sql);

        List<Long> objectArrayList = query.getResultList();
        em.close();
        return objectArrayList;
    }
}